from utils.network import UpgradeInterface
import json
import random
import os
from utils import memory
from utils.model import User, Message


class API(UpgradeInterface):

    def handle(self, req):
        recipients = req['recipients']
        file_name = req['file_name']
        message_template = '<file>{}</file>'
        if 'as_image' in req and req['as_image'] is True:
            message_template = '<image>{}</image>'
        file_id = str(hex(random.randint(16 ** 7, 16 ** 8 - 1)))[2:]
        res = self.success_respond({
            'file_id': file_id
        })
        os.makedirs('./.cache/{}'.format(file_id))
        file_path = './.cache/{}/{}'.format(file_id, file_name)
        f = open(file_path, 'wb')
        self._conn.send(json.dumps(res).encode('utf-8'))
        while True:
            data = self._conn.recv(1000000)
            if len(data) == 0:
                break
            f.write(data)
        f.close()
        for account in recipients:
            recipient = memory.users[account]
            sender = self.user
            assert isinstance(recipient, User)
            assert isinstance(sender, User)
            message = Message(sender.account, recipient.account,
                              message_template.format(json.dumps({
                                  'file_id': file_id,
                                  'file_name': file_name,
                                  'total_bytes': os.stat(file_path).st_size
                              })))
            recipient.recv_messages.append(message)
            sender.recv_messages.append(message)
        memory.files[file_id] = {
            'file_path': file_path
        }
